import { getLocalStorage } from '../../utils.js'
Page({
  data: {
    value: null, // null代表数据库没有记录，0代表数据库有记录但是余额为0
    openid: null, // null代表未登录
    items: ['30元', '60元', '90元', '120元', '150元', '200元']
  },
  async handler (e) {
    let money = parseFloat(e.currentTarget.dataset.value)
    const openid = await getLocalStorage('openid')
    wx.showLoading({ title: '加载中', mask: true })
    if(!!openid) {
      if (this.data.value === null) {
        await wx.cloud.callFunction({ name: 'rh', data: { type: 'addTotalMoney', openid, money }})
      } else {
        money = money + this.data.value
        await wx.cloud.callFunction({ name: 'rh', data: { type: 'updateTotalMoney', openid, money }})
      }
      // if (r && r.stats && r.stats.updated) {
      //   this.setData({ value: money })
      // }
      setTimeout(() => {
        wx.hideLoading()
        this.setData({ value: money })
        wx.showToast({ title: '充值成功', icon: 'success' })
      }, 1000)
    } else {
      setTimeout(() => {
        wx.hideLoading()
        wx.showToast({ title: '充值失败-未登录', icon: 'error' })
      }, 1000)
    }
  },
  async onReady() {
    wx.showLoading({ title: '加载中', mask: true })
    const openid = await getLocalStorage('openid')
    if (!!openid) {
      const { result } = await wx.cloud.callFunction({ name: 'rh', data: { type: 'getTotalMoney', openid } })
      !!result && this.setData({ value: result.money })
    }
    wx.hideLoading()
  }
})